package com.water.app.Controller.chat;

import com.water.app.Constant;
import com.water.app.Impl.aiChat.AiChatMemoryImpl;
import com.water.app.QiniuUtil;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.content.Media;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;

import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@RestController
@RequestMapping("/api/ai")
public class ChatAiController {

    private static final Logger log = LoggerFactory.getLogger(ChatAiController.class);
    //最大携带上下文数
    private final int MAX_MESSAGE=20;

    private QiniuUtil qiniuUtil;

    private final AiChatMemoryImpl aiChatMemory;

    private final ChatClient chatClient;
    public ChatAiController(AiChatMemoryImpl aiChatMemory, QiniuUtil qiniuUtil){
        this.aiChatMemory=aiChatMemory;
        this.chatClient = aiChatMemory.getChatClient();
        this.qiniuUtil=qiniuUtil;
    }

    private final String system="你是优购商城的一名可爱的客服，你要耐心的根据用" +
            "户的提问来生成sql语句查询数据库,并且根据查询的数据库的信息" +
            "耐心的回答用户的问题，如果用户想让你陪他聊天，也可以陪用户聊天。" +
            "另外，用户也可能发图片给你，你要综合图片和文字一起回答用户。";

    private final String TABLE_STRUCTURE="CREATE TABLE `goods` (\n" +
            "  `id` int unsigned NOT NULL AUTO_INCREMENT COMMENT '商品id',\n" +
            "  `picture` varchar(600) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'https://picsum.photos/300/300?random=11' COMMENT '商品图片',\n" +
            "  `name` varchar(20) NOT NULL COMMENT '商品名称',\n" +
            "  `count` int NOT NULL COMMENT '商品数量',\n" +
            "  `description` varchar(200) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '商品描述',\n" +
            "  `price` double NOT NULL COMMENT '商品价格',\n" +
            "  `type` int NOT NULL COMMENT '商品类型',\n" +
            "  `userId` int NOT NULL COMMENT '是哪个用户发布的',\n" +
            "  `version` int NOT NULL DEFAULT '0',\n" +
            "  `shop_goods_type` int NOT NULL COMMENT '用户自定义商品种类id',\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  UNIQUE KEY `id` (`id`),\n" +
            "  UNIQUE KEY `itemCode` (`picture`),\n" +
            "  UNIQUE KEY `name` (`name`)\n" +
            ") ENGINE=InnoDB AUTO_INCREMENT=25 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='商品表';"+
            "CREATE TABLE `orders` (\n" +
            "  `id` int NOT NULL AUTO_INCREMENT COMMENT '主键id',\n" +
            "  `goodsId` int NOT NULL COMMENT '商品id，与goods表的id对应',\n" +
            "  `number` int NOT NULL COMMENT '商品数量',\n" +
            "  `status` int DEFAULT '0' COMMENT '订单状态',\n" +
            "  `time` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '订单时间',\n" +
            "  `picture` varchar(200) NOT NULL COMMENT '商品图片',\n" +
            "  `price` double NOT NULL COMMENT '商品总价',\n" +
            "  `userId` int NOT NULL COMMENT '用户id,与user表的id对应',\n" +
            "  PRIMARY KEY (`id`)\n" +
            ") ENGINE=InnoDB AUTO_INCREMENT=58 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='订单表';"+
            "CREATE TABLE `user` (\n" +
            "  `id` int NOT NULL AUTO_INCREMENT COMMENT '用户id',\n" +
            "  `username` varchar(20) NOT NULL COMMENT '用户名',\n" +
            "  `password` varchar(20) NOT NULL COMMENT '密码',\n" +
            "  `email` varchar(20) NOT NULL COMMENT '邮箱',\n" +
            "  `account` varchar(20) NOT NULL COMMENT '账号',\n" +
            "  `money` double NOT NULL COMMENT '钱包金额',\n" +
            "  `version` int NOT NULL DEFAULT '0',\n" +
            "  `picture` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL DEFAULT 'https://p3.ssl.qhimgs1.com/t04c8dbbb4ce1c29919.png' COMMENT '用户头像',\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  UNIQUE KEY `username` (`username`),\n" +
            "  UNIQUE KEY `email` (`email`),\n" +
            "  UNIQUE KEY `account` (`account`)\n" +
            ") ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户表';"+
            "CREATE TABLE `shop` (\n" +
            "  `id` int NOT NULL AUTO_INCREMENT COMMENT '店铺id',\n" +
            "  `name` varchar(100) NOT NULL COMMENT '店铺名称',\n" +
            "  `picture` varchar(200) DEFAULT 'https://p0.ssl.qhimgs1.com/t043ba1199a69fa6106.jpg' COMMENT '店铺图片',\n" +
            "  `description` varchar(100) DEFAULT '欢迎来到我的店铺' COMMENT '商品描述',\n" +
            "  `userId` int NOT NULL COMMENT '用户id,关联user表的id',\n" +
            "  PRIMARY KEY (`id`),\n" +
            "  UNIQUE KEY `id` (`id`),\n" +
            "  UNIQUE KEY `name` (`name`)\n" +
            ") ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci COMMENT='用户开的店铺的表';";
    //ai聊天测试版
    @PostMapping("/chat")
    public SseEmitter ChatStream(@RequestParam(value = "prompt",required = false)String question,
                             @RequestParam(value = "picture",required = false)MultipartFile picture) throws Exception {
        SseEmitter sseEmitter=new SseEmitter();
        Integer userId = Constant.THREAD_LOCAL.get();
        String url;
        if (picture!=null&&!picture.isEmpty()) {
            url = qiniuUtil.uploadImage(picture, "aiChat/", "user/" + userId);
            aiChatMemory.setMediaList(
                    List.of(
                            //直接new url被弃用了
                            new Media(MimeTypeUtils.IMAGE_PNG,new URI(url).toURL().toURI())
                    )
            );
        }else {
            url = null;
            log.info("图片为空，不校验");
        }
        aiChatMemory.setSystem(system);
        aiChatMemory.setMAX_MESSAGE(MAX_MESSAGE);
        aiChatMemory.setTABLE_STRUCTURE(TABLE_STRUCTURE);


        Flux<String> flux = aiChatMemory.MySqlChatMemoryStream(question, url, userId);
        flux.subscribe(
                chunk -> {
                    try {
                        sseEmitter.send(chunk);
                    } catch (IOException e) {
                        sseEmitter.completeWithError(e);
                    }
                },
                error -> sseEmitter.completeWithError(error),
                () -> sseEmitter.complete()
        );

        return sseEmitter;
    }
    
    @PostMapping("/chatString")
    public String chatString(@RequestParam(value = "prompt",required = false)String question,
                             @RequestParam(value = "picture",required = false)MultipartFile picture) throws IOException, URISyntaxException {
        Integer userId = Constant.THREAD_LOCAL.get();
        String url = qiniuUtil.uploadImage(picture, "aiChat/", "user/" + userId);
        aiChatMemory.setMediaList(
                List.of(
                        //直接new url被弃用了
                        new Media(MimeTypeUtils.IMAGE_PNG,new URI(url).toURL().toURI())
                )
        );
        aiChatMemory.setSystem(system);
        aiChatMemory.setMAX_MESSAGE(MAX_MESSAGE);
        aiChatMemory.setTABLE_STRUCTURE(TABLE_STRUCTURE);
        return aiChatMemory.MySqlChatMemory(question, url, userId);
    }
    
}
